$import([ 'com.hh.form.PropertyGridPanel',
		'com.hh.form.actionform.PageListPanel' ]);
Ext
		.define(
				'com.hh.workflow.form.WorkFlowPageEdit',
				{
					extend : 'com.hh.global.SimpleFormPanelWindow',
					action : 'form-ActionForm-',
					title : '编辑',
					width : 800,
					height : 400,
					submitMethod : 'workflowSave',
					entityKey : 'id',
					constructor : function(config) {
						this.config = config || {};
						if (this.config.parentPanel == null) {
							this.config.parentPanel = {};
							if (this.config.formDataId != null) {
								this.config.parentPanel.hhXtForm = this.config.parentPanel.hhXtForm = Request
										.synRequestObject(
												"form-FormWidget-findObjectByDataId",
												{
													dataId : this.config.formDataId
												});
							}
						}
						this.superclass.constructor.call(this, this.config);
						this.fieldBlurList = [];
						this.init();
						if (this.actionType == 'manager') {
							this.addWorkFlowTree();
						}
						this.setFormManager();
					},
					setFormManager : function() {
						var page = this;
						var formManagerList = [];
						if (page.actConfig.formManager) {
							formManagerList = Ext
									.decode(page.actConfig.formManager);
						}
						var form = this.form.getForm();
						for ( var i = 0; i < formManagerList.length; i++) {
							var formManager = formManagerList[i];
							var field = form.findField(formManager.name);
							if (field) {
								if (formManager.readOnly) {
									field.setReadOnly(formManager.readOnly);
								}
								if (formManager.hidden) {
									field.setHidden(formManager.hidden);
								}
							}
						}
					},
					treecheckchange : function(node, checked, isnotcheck) {
						var page = this;
						var isChange = node.raw.propertys.isChange;
						if (!isnotcheck) {
							if (isChange == false) {
								node.set('checked', !checked);
								ExtFrame.info("您不能选择步骤！！（您没有权限选择步骤）");
								return;
							}
						}
						var activityParentType = node.raw.propertys.activityParentType;
						var activityType = node.raw.propertys.activityType;
						var parentNode = node.parentNode;
						if (checked == false) {
							TreeUtil.selectChildNodes(node, false);
							if ("parallelGateway" == activityParentType) {
								var childNodes = parentNode.childNodes;
								for ( var i = 0; i < childNodes.length; i++) {
									childNodes[i].set('checked', checked);
									TreeUtil.selectChildNodes(childNodes[i],
											checked);
								}
							}
							if (activityType == "parallelGateway") {
								TreeUtil.selectChildNodes(node, checked);
							}
						} else {
							if (TreeUtil.isSelectParentNode(node) == false) {
								ExtFrame.info("请先选中父节点！");
								node.set('checked', !checked);
								return;
							}
							if (parentNode != null) {
								var childNodes = parentNode.childNodes;
								for ( var i = 0; i < childNodes.length; i++) {
									if ('exclusiveGateway' == activityParentType) {
										if (childNodes[i] != node) {
											childNodes[i].set('checked', false);
											TreeUtil.selectChildNodes(
													childNodes[i], false);
										}
									} else if ("parallelGateway" == activityParentType) {
										childNodes[i].set('checked', checked);
										TreeUtil.selectChildNodes(
												childNodes[i], checked);
									}
								}
							}
							if (activityType == "parallelGateway") {
								TreeUtil.selectChildNodes(node, checked);
							}
						}
						var workFlowSetpTreeRootNode = page.workFlowSetpTree
								.getRootNode();
						page.selectChildNodes(workFlowSetpTreeRootNode);
					},
					addWorkFlowTree : function() {
						var page = this;
						var tree = Ext
								.create(
										'com.hh.global.SimpleTreePanel',
										{
											region : 'west',
											padding : '0',
											getTbar : function() {
												return [ {
													icon : '/common/images/icons/lock/lock_open.png',
													text : '按表单选择步骤',
													handler : Ext
															.bind(
																	page.callFieldBlurList,
																	page)
												} ];
											},
											getTreePanelListeners : function() {
												return {
													checkchange : function(
															node, checked) {
														page.treecheckchange(
																node, checked);
													},
													load : function() {
														var workFlowSetpTreeRootNode = tree.tree
																.getRootNode();
														page
																.selectChildNodes(workFlowSetpTreeRootNode);
														page
																.registerEvent(
																		workFlowSetpTreeRootNode,
																		workFlowSetpTreeRootNode);
													}
												};
											},
											title : '请选择步骤',
											query_action : 'workflow-Task-queryStepByActivityId',
											extraParams : {
												pdid : page.pdid,
												activityId : page.activityId,
												piid : page.piid
											}
										});

						this.workFlowSetpTree = tree.tree;
						page.add(tree);
					},
					registerEvent : function(node, rootNode) {
						var page = this;
						var form = page.form.getForm();
						var childNodes = node.childNodes;
						for ( var i = 0; i < childNodes.length; i++) {
							var childNode = childNodes[i];
							var propertys = childNode.raw.propertys;
							var condition = propertys.condition;
							var expressionKeyList = propertys.expressionKeyList;
							if (expressionKeyList) {
								for ( var j = 0; j < expressionKeyList.length; j++) {
									var expressionKey = expressionKeyList[j];
									var field = form.findField(expressionKey
											.replace("formObject.", ""));
									if (field) {
										var fieldBlur = Ext.bind(
												page.fieldBlur, page, [
														condition, childNode ])
										page.fieldBlurList.push(fieldBlur);
										fieldBlur();
										field.on("change", fieldBlur);
									}
								}
							}
							page.registerEvent(childNode, rootNode);
						}
					},
					fieldBlur : function(condition, node) {
						var page = this;
						var formObject = page.form.getValues();
						node.set('checked', eval(condition));
						page.treecheckchange(node, eval(condition), true);
					},
					loadComment : function() {
						var page = this;
						Request
								.request(
										'workflow-Task-queryCommentByPiidAndTaskId',
										{
											piid : page.piid,
											taskId : page.taskId
										},
										function(result) {
											var workFlowComment = page.form
													.getForm().findField(
															"workFlowComment");
											workFlowComment
													.setValue(result.comment);
											var tpl = Ext
													.create(
															'Ext.XTemplate',
															'<tpl for=".">',
															'<span class=labelText>节点名称：</span>{activityName}<br/>',
															'<span class=labelText>创建人：</span>{userName}<br/>',
															'<span class=labelText>时间：</span>{time}<br/>',
															'<span class=labelText>内容：</span>{message}<hr/>',
															'</tpl>');
											workFlowComment
													.nextSibling()
													.update(
															tpl
																	.apply(result.commentList));
										});
					},
					loadData : function(id) {
						var page = this;
						if (page.actConfig.comment != true) {
							this.loadComment();
						}
						var hhXtForm = this.config.parentPanel.hhXtForm;
						Request.request(this.action + this.editAction, {
							id : id,
							tableName : hhXtForm.tableName
						}, function(object) {
							page.object = object;
							FormPanel.setValues(page.form, page.object);
							page.afDataLoad(id);
						});
					},
					afDataLoad : function(id) {
						this.form.getForm().findField("id").setValue(id);
						if (this.object == null) {
							this.form.getForm().findField("saveType").setValue(
									"insert");
						} else {
							this.form.getForm().findField("saveType").setValue(
									"update");
						}
					},
					getFormItems : function() {
						var page = this;
						var hhXtForm = this.config.parentPanel.hhXtForm;
						var formWidgetList = Ext.decode(hhXtForm.formSource);
						if (page.actConfig.comment != true
								|| page.actConfig.attachment != true) {
							formWidgetList.push(this.getOpinionFormSet());
						}
						if (this.actionType == 'manager') {
							formWidgetList.push(this.getWorklowSubmitFormSet());
						}
						formWidgetList.push({
							name : 'id',
							hidden : true
						});
						formWidgetList.push({
							fieldLabel : 'dataId',
							name : 'dataId',
							hidden : true,
							value : hhXtForm.dataId
						});
						formWidgetList.push({
							fieldLabel : 'saveType',
							name : 'saveType',
							hidden : true
						});
						return formWidgetList;
					},
					getWorklowSubmitFormSet : function() {
						var page = this;

						this.workFlowFieldSet = Ext.create("Ext.form.FieldSet",
								{
									xtype : 'fieldset',
									collapsible : true,
									title : '流程转交',
									defaults : {
										labelWidth : 70,
										xtype : 'textfield',
										margin : '5 3 5 3'
									},
									layout : "column",
									bodyPadding : '5 5 0',
									columnWidth : 1
								});

						return page.workFlowFieldSet;
					},
					getGridColumns : function() {
						var page = this;
						return [
								{
									header : 'path',
									dataIndex : 'path',
									flex : 1,
									hidden : true
								},
								{
									dataIndex : 'id',
									flex : 1,
									hidden : true
								},
								{
									text : '名称',
									dataIndex : 'attachmentFileName',
									flex : 1,
									renderer : function(value, p, data) {
										return Ext.String
												.format(
														'<a href="javascript:Href.download(\''
																+ data.data.attachmentFileName
																+ '\',\''
																+ data.data.path
																+ '\');">{0}</a>',
														value);
									}
								},
								{
									text : '描述',
									dataIndex : 'name',
									flex : 1
								},
								{
									text : '节点',
									dataIndex : 'type',
									flex : 1
								},
								{
									text : '用户',
									dataIndex : 'userName',
									flex : 1
								},
								{
									text : '操作',
									menuDisabled : true,
									sortable : false,
									xtype : 'actioncolumn',
									width : 50,
									items : [ {
										iconCls : 'delete',
										tooltip : '删除',
										handler : function(grid, rowIndex,
												colIndex) {
											var rec = grid.getStore().getAt(
													rowIndex);
											if (loginUser.id == rec
													.get("userId")
													&& page.taskId == rec
															.get("taskId")
													|| rec.get("userId") == null
													|| rec.get("userId") == '') {
												Request
														.request(
																'workflow-File-delete',
																{
																	id : rec
																			.get("id")
																},
																function(result) {
																	if (result.isSuccess == true) {
																		grid
																				.getStore()
																				.remove(
																						rec);
																	}
																},
																{
																	isDefaultMsg : true
																});
											} else {
												ExtFrame.msg(
														"您只能删除本节点并且是自己添加的附件！！",
														3000);
											}
										}
									} ]
								} ];
					},
					doAddAttachment : function() {
						var page = this;
						Desktop.openWindow("com.hh.global.widget.FileWindow", {
							addWindow : false,
							filePath : 'workflow/' + page.pdName,
							url : 'workflow-File-save?taskId=' + page.taskId
									+ '&piid=' + page.piid + '&type='
									+ page.actName + '',
							parentPanel : page
						});
					},
					getOpinionFormSet : function() {
						var page = this;

						var items = [];

						if (page.actConfig.attachment != true) {
							var proxy = ExtStore.getGridStoreProxyByObject({
								url : 'workflow-File-queryAttachmentPiid',
								extraParams : {
									piid : page.piid
								}
							});
							var store = Ext
									.create('com.hh.base.BaseDataStore',
											{
												pageSize : static_var.pageSize,
												fields : [ 'id', 'type',
														'name',
														'attachmentFileName',
														'path', 'userName',
														'userId', 'taskId' ],
												proxy : proxy
											});
							var gridConfig = {
								columns : this.getGridColumns(),
								columnWidth : 1,
								border : 1,
								store : store,
								tbar : [ {
									iconCls : 'add',
									text : '添加附件',
									handler : function() {
										page.doAddAttachment();
									}
								}, {
									iconCls : 'refresh',
									text : '刷新',
									handler : function() {
										page.grid.getStore().load();
									}
								} ]
							};
							var grid = this.grid = Ext.create(
									'com.hh.base.BaseGridPanel', gridConfig);
							items.push(grid);
						}
						if (page.actConfig.comment != true) {
							items.push({
								xtype : 'htmleditor',
								columnWidth : 1,
								name : 'workFlowComment',
								hidden : page.actionType == 'select'
							});
							items.push({
								xtype : 'fieldset',
								columnWidth : 1,
								collapsible : true,
								title : '历史意见'
							});
						}
						return {
							xtype : 'fieldset',
							collapsible : true,
							title : '流程意见和附件',
							defaults : {
								labelWidth : 70,
								xtype : 'textfield',
								margin : '5 3 5 3'
							},
							layout : "column",
							bodyPadding : '5 5 0',
							columnWidth : 1,
							items : items
						};
					},
					getBtns : function() {
						var page = this;
						if (page.actionType == 'select') {
							return null;
						}
						return [
								{
									icon : 'struts-image?path=com/hh/form/img/xhtml_go.png',
									text : '提交',
									handler : function() {
										page.submitForm(1);
									}
								},
								{
									iconCls : 'add',
									text : '添加经办人',
									handler : function() {
										var window = Ext.create(
												'com.hh.base.BaseWindow', {
													title : '添加经办人',
													width : 500,
													height : 120,
													modal : true
												}).show();
										var form = Ext
												.create(
														'com.hh.base.BaseFormPanel',
														{
															url : 'workflow-Task-addTaskUser',
															items : [
																	{
																		xtype : 'widgetUserSelect',
																		fieldLabel : '选择经办人',
																		name : 'userStrIds'
																	},
																	{
																		name : 'taskId',
																		hidden : true,
																		value : page.taskId
																	} ],
															buttons : [
																	{
																		iconCls : 'yes',
																		text : '保    存',
																		handler : function() {
																			FormPanel
																					.submit(form);
																			window
																					.close();
																		}
																	},
																	{
																		iconCls : 'cancel',
																		text : '取    消',
																		handler : function() {
																			window
																					.close();
																		}
																	} ]
														});
										window.add(form);
									}
								},
								{
									icon : 'struts-image?path=com/hh/workflow/img/shape_square_edit.png',
									text : '领取',
									handler : function() {
										Request.request('workflow-Task-claim',
												{
													taskId : page.taskId
												}, null, {
													isDefaultMsg : true
												});
									}
								}, {
									iconCls : 'search',
									text : '查看历史',
									handler : function() {
										page.doSelectHi();
									}
								}, this.getBtnByType("save"),
								this.getBtnByType("cancel") ];
					},
					doSelectHi : function() {
						var page = this;
						var win = ExtUtil.create(
								'com.hh.workflow.task.HiTaskList', {
									id : this.id
											+ '-'
											+ 'com.hh.workflow.task.HiTaskList'
													.replace(/\./g, ''),
									parentPanel : this,
									extraParams : {
										piid : page.piid,
										pdid : page.pdid
									}
								});
						win.show();
					},
					submitForm : function(type) {
						var page = this;
						FormPanel
								.submit(
										this.form,
										{
											callback : function(result) {
												if (result.success = true && result.object != null) {
													if (result.object.id != null) {
														page.form
																.getForm()
																.findField(
																		"saveType")
																.setValue(
																		"update");
														page.saveComment(type,
																result);
													}
												} else {
													ExtFrame.info(result.msg);
												}
											}
										});
					},
					saveComment : function(type, saveFormResult) {
						var page = this;
						if (page.actConfig.comment != true) {
							var workFlowComment = page.form.getForm()
									.findField("workFlowComment");
							Request
									.synRequestObject(
											'workflow-Task-saveComment',
											{
												taskId : page.taskId,
												piid : page.piid,
												workFlowComment : workFlowComment
														.getValue()
											},
											function(result) {
												if (result.success = true) {
													if (type == 1) {
														page
																.workFlowTaskSubmit(saveFormResult);
													} else {
														Ext.example.msg('提示',
																'保存成功！！');
													}
												}
											});
						} else {
							if (type == 1) {
								page.workFlowTaskSubmit(saveFormResult);
							} else {
								Ext.example.msg('提示', '保存成功！！');
							}
						}
					},
					callFieldBlurList : function() {
						var page = this;
						for ( var i = 0; i < page.fieldBlurList.length; i++) {
							page.fieldBlurList[i]();
						}
					},
					workFlowTaskSubmit : function(result) {
						var page = this;
						page.callFieldBlurList();
						var userItems = page.workFlowFieldSet.items.items;
						for ( var i = 0; i < userItems.length; i++) {
							if (userItems[i].getValue() == null
									|| userItems[i].getValue() == '') {
								ExtFrame.msg("节点："
										+ userItems[i].getFieldLabel()
										+ "；用户不能为空，请选择用户！！", 3000);
								return;
							}
						}
						result.object.taskId = page.taskId;
						result.object.piid = page.piid;

						var workFlowSetpTreeRootNode = page.workFlowSetpTree
								.getRootNode();

						var conditionMap = {};
						page.addConditionMap(workFlowSetpTreeRootNode,
								conditionMap);
						if (conditionMap.isSubmit != true
								&& conditionMap.isUserTask == true) {
							ExtFrame.msg("请选择步骤！！");
							return;
						}
						var resultObjectParams = result.object;
						Ext.apply(resultObjectParams, conditionMap);
						Request
								.synRequestObject(
										'workflow-Task-submit',
										resultObjectParams,
										function(resultObject) {
											if (resultObject.success == false
													|| resultObject.success == true) {
												if (resultObject.success == true
														&& resultObject.msg == null
														&& resultObject.returnModel == null) {
													page.close();
												} else {
													if (resultObject.msg) {
														ExtFrame
																.msg(
																		resultObject.msg,
																		3000);
													} else {
														ExtFrame
																.msg(
																		resultObject.returnModel.msg,
																		3000);
													}

												}
											}
										});
					},
					addConditionMap : function(node, map) {
						if (node != null) {
							var childNodes = node.childNodes;
							for ( var i = 0; i < childNodes.length; i++) {
								if (childNodes[i].get('leaf') == true) {
									map['isUserTask'] = true;
								}
								if (childNodes[i].get('leaf') == true
										&& childNodes[i].get('checked') == true) {
									map['isSubmit'] = true;
								}
								if (childNodes[i].raw.propertys.sdxz_condition == true) {
									map['conditionMap.'
											+ childNodes[i].get("id")] = childNodes[i]
											.get('checked') == true ? 1 : 0;
								}
								this.addConditionMap(childNodes[i], map);
							}
						}
					},
					selectChildNodes : function(node) {
						var page = this;
						if (node != null) {
							var childNodes = node.childNodes;
							for ( var i = 0; i < childNodes.length; i++) {
								var childNode = childNodes[i];
								var propertys = childNode.raw.propertys;
								if (childNode.get("leaf") == true) {
									var itemSelector = page.form.getForm()
											.findField(
													'userMap.candidateUsers_'
															+ childNodes[i]
																	.get("id"));
									if (childNode.get('checked') == true) {
										if (itemSelector == null) {
											var result = Request
													.synRequestObject(
															'workflow-Task-queryHiAssigneesByActIdAndPiid',
															{
																piid : page.piid,
																activityId : propertys.activityId
															});
											itemSelector = Ext
													.create(
															"com.hh.usersystem.user.UserSelect",
															{
																value : result,
																name : 'userMap.candidateUsers_'
																		+ childNode
																				.get("id"),
																xtype : 'widgetUserSelect',
																roles : propertys.roles,
																users : propertys.users,
																orgs : propertys.orgs,
																isorg : propertys.isorg,
																isrole : propertys.isrole,
																fieldLabel : childNode
																		.get(
																				"text")
																		.replace(
																				"（任务节点）",
																				"")
															});
											page.workFlowFieldSet
													.add(itemSelector);
										}
									} else {
										if (itemSelector != null) {
											page.workFlowFieldSet
													.remove(itemSelector);
										}
									}
								}

								this.selectChildNodes(childNodes[i]);
							}
						}
					}
				});